package com.multicampus.simplewiki.search;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;

import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.cjk.CJKAnalyzer;
import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.highlight.Highlighter;
import org.apache.lucene.search.highlight.QueryScorer;
import org.apache.lucene.search.highlight.SimpleHTMLEncoder;
import org.apache.lucene.search.highlight.SimpleHTMLFormatter;
import org.apache.lucene.search.highlight.TokenSources;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

import com.multicampus.simplewiki.vo.SearchListVO;
import com.multicampus.simplewiki.vo.SearchResultVO;

public class DocumentSearcher implements Searcher<SearchResultVO>{
	public DocumentSearcher() {
	
	}

	public SearchListVO<SearchResultVO> search(String queryString, int startPage, int count) throws Exception{
		Directory directory = FSDirectory.getDirectory(new File("/db/index"));
		IndexSearcher searcher = new IndexSearcher(directory);
		MultiFieldQueryParser parser = new MultiFieldQueryParser(new String[]{"title", "content", "tags", "username"}, new CJKAnalyzer());
		Query query = parser.parse(queryString);
		
		Hits hits = searcher.search(query);
		
		SimpleHTMLFormatter htmlFormatter = new SimpleHTMLFormatter();
		Highlighter highlighter = new Highlighter(htmlFormatter, new QueryScorer(query));
		highlighter.setEncoder(new SimpleHTMLEncoder());
		SearchListVO<SearchResultVO> searchList = new SearchListVO<SearchResultVO>();
		Collection<SearchResultVO> results = new ArrayList<SearchResultVO>();
		
		for (int i = (startPage - 1) * count; i < (startPage * count) && i < hits.length(); i++) {
			SearchResultVO searchResult = new SearchResultVO();
			String text = hits.doc(i).get("content");
			TokenStream tokenStream = TokenSources.getAnyTokenStream(searcher.getIndexReader(), hits.id(i), "content", new CJKAnalyzer());
			String frag = highlighter.getBestFragment(tokenStream, text);
			searchResult.setContents(frag);
			searchResult.setTitle(hits.doc(i).get("title"));
			searchResult.setId(hits.doc(i).get("id"));
			
			results.add(searchResult);
		}
		
		searchList.setSearchResults(results);
		searchList.setTotalCount(hits.length());
		searchList.setCurrentPage(startPage);
		
		return searchList;
	}
}
